from django.shortcuts import render


# Create your views here.

def index(request):
    return render(request, "index.html")


def search(request):  # 查找火车的爬虫(最短时间)
    import requests
    import json
    import re
    import os
    # 站点信息

    url = "https://kyfw.12306.cn/otn/leftTicket/queryT"

    url2 = "https://kyfw.12306.cn/otn/resources/js/framework/station_name.js?station_version=1.9207"

    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.198 Safari/537.36',
        'Referer': 'https://kyfw.12306.cn/otn/leftTicket/init?linktypeid=wf',
        'Cookie': '_uab_collina=163077338623568853680117; JSESSIONID=2F34A4A8F36A2664D16E3D530A8C409A; BIGipServerotn=1089470986.50210.0000; RAIL_EXPIRATION=1631049192249; RAIL_DEVICEID=M8sa8Kq70vKSYxrnRGUb8LfnYvheI7g5wspaDkGezBtmLQJ_J_T0ge43HEBOCkMR8UTqXHEYRROGvApGh3x23cvHptlSQogWfOEaf7N2oaX6H-GTrXXK-qa-lhUkTxo8oWuXhl8Ctb5eN0LM5uu96xs9AN4Lro1_; guidesStatus=off; highContrastMode=defaltMode; cursorStatus=off; BIGipServerpool_passport=199492106.50215.0000; route=9036359bb8a8a461c164a04f8f50b252; _jc_save_fromStation=%u4E0A%u6D77%2CSHH; _jc_save_toStation=%u5317%u4EAC%2CBJP; _jc_save_fromDate=2021-09-05; _jc_save_toDate=2021-09-05; _jc_save_wfdc_flag=wf'
    }

    date = request.GET.get("date")

    fs = request.GET.get("input_city")

    ts = request.GET.get("input_city1")

    resp2 = requests.get(url=url2)

    chezhan = re.findall(r'([\u4e00-\u9fa5]+)\|([A-Z]+)', resp2.text)

    chezhan_code = dict(chezhan)

    chezhan_names = dict(zip(chezhan_code.keys(), chezhan_code.values()))

    from_station = chezhan_names[fs]
    to_station = chezhan_names[ts]
    params = {
        'leftTicketDTO.train_date': date,
        'leftTicketDTO.from_station': from_station,
        'leftTicketDTO.to_station': to_station,
        'purpose_codes': "ADULT"
    }

    resp = requests.get(url=url, headers=headers, params=params)

    data = json.loads(resp.content)
    str = '查询结果：\n'
    min = "99:99"
    for i in data['data']['result']:
        temp_list = i.split('|')
        # 无座     26
        # 软座     23
        # 硬座     29
        # 硬卧     28
        temp_list = i.split('|')
        if temp_list[10] <= min:
            min = temp_list[10]
            str1 = temp_list[3]
            fctime = temp_list[9]
        # str += temp_list[3] + ':'
        # str += '发车时间：' + temp_list[8]
        # str += '到达时间：' + temp_list[9]
        # str += '历时：' + temp_list[10]
        # str += "\n"
        str = "列车车次：" + str1 + " 历时：" + min + " 发车时间：" + fctime
    return render(request, "search.html", {"str": str})

def search1(request):
    return render(request,"test1.html")

def search2(request):
    return render(request,"test2.html")

def search_money(request):            #最少花费
    import requests
    import json
    import re
    import os
    import time
    import random
    # 站点信息

    url = "https://kyfw.12306.cn/otn/leftTicket/queryT"

    url2 = "https://kyfw.12306.cn/otn/resources/js/framework/station_name.js?station_version=1.9207"

    url3 = "https://kyfw.12306.cn/otn/leftTicket/queryTicketPrice"

    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.198 Safari/537.36',
        'Referer': 'https://kyfw.12306.cn/otn/leftTicket/init?linktypeid=wf',
        'Cookie': '_uab_collina=163077338623568853680117; JSESSIONID=2F34A4A8F36A2664D16E3D530A8C409A; BIGipServerotn=1089470986.50210.0000; RAIL_EXPIRATION=1631049192249; RAIL_DEVICEID=M8sa8Kq70vKSYxrnRGUb8LfnYvheI7g5wspaDkGezBtmLQJ_J_T0ge43HEBOCkMR8UTqXHEYRROGvApGh3x23cvHptlSQogWfOEaf7N2oaX6H-GTrXXK-qa-lhUkTxo8oWuXhl8Ctb5eN0LM5uu96xs9AN4Lro1_; guidesStatus=off; highContrastMode=defaltMode; cursorStatus=off; BIGipServerpool_passport=199492106.50215.0000; route=9036359bb8a8a461c164a04f8f50b252; _jc_save_fromStation=%u4E0A%u6D77%2CSHH; _jc_save_toStation=%u5317%u4EAC%2CBJP; _jc_save_fromDate=2021-09-05; _jc_save_toDate=2021-09-05; _jc_save_wfdc_flag=wf'
    }

    date = request.GET.get("date")

    fs = request.GET.get("input_city")

    ts = request.GET.get("input_city1")

    resp2 = requests.get(url=url2)

    chezhan = re.findall(r'([\u4e00-\u9fa5]+)\|([A-Z]+)', resp2.text)

    chezhan_code = dict(chezhan)

    chezhan_names = dict(zip(chezhan_code.keys(), chezhan_code.values()))

    from_station = chezhan_names[fs]
    to_station = chezhan_names[ts]
    params = {
        'leftTicketDTO.train_date': date,
        'leftTicketDTO.from_station': from_station,
        'leftTicketDTO.to_station': to_station,
        'purpose_codes': "ADULT"
    }

    resp = requests.get(url=url, headers=headers, params=params)

    data = json.loads(resp.content)
    if len(data["data"]["result"]) == 0:
        str1 = "您查询的时间没有在起点和目的地之间的车次安排！"
    else:

        lprice = 10000
        lprice_no = ""
        for i in data["data"]["result"]:
            temp_list = i.split('|')
            train_no = temp_list[2]
            from_station_no = temp_list[16]
            to_station_no = temp_list[17]
            seat_types = temp_list[35]
            params1 = {
                'train_no': train_no,
                'from_station_no': from_station_no,
                'to_station_no': to_station_no,
                'seat_types': seat_types,
                'train_date': date,
            }
            resp3 = requests.get(url=url3, headers=headers, params=params1)
            data3 = json.loads(resp3.content)

            flag = 1
            for i in seat_types:
                if i == 'O' or i == 'M':
                    flag = 0
            if flag == 1:
                price = data3["data"]["A1"]
                price = price[1:]
                price = price[:-2]
                if int(price) <= int(lprice):
                    lprice = price
                    lprice_no = temp_list[3]
            random_time = random.uniform(1.2, 1.5)        #设置随机数的休眠时间以防止被限制
            time.sleep(random_time)
        lprice_str = str(lprice)

        if int(lprice) == 10000:
            for i in data["data"]["result"]:
                temp_list = i.split('|')
                train_no = temp_list[2]
                from_station_no = temp_list[16]
                to_station_no = temp_list[17]
                seat_types = temp_list[35]
                params1 = {
                    'train_no': train_no,
                    'from_station_no': from_station_no,
                    'to_station_no': to_station_no,
                    'seat_types': seat_types,
                    'train_date': date,
                }
                resp3 = requests.get(url=url3, headers=headers, params=params1)
                data3 = json.loads(resp3.content)
                price = data3["data"]["O"]
                price = price[1:]
                price = price[:-2]
                if int(price) <= int(lprice):
                    lprice = price
                    lprice_no = temp_list[3]
                random_time = random.uniform(3.0, 3.5)  # 设置随机数的休眠时间以防止被限制
                time.sleep(random_time)
            lprice_str = str(lprice)


        str1 = "推荐车次：" + lprice_no + " 价格：" + lprice_str +"元"
    return render(request, "search.html", {"str": str1})